﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Waker.APIs.ADS;
using Waker.Common;
using Waker.Entitys;

namespace Waker.Devices
{
    public partial class FormDeviceSearch : Base.FormBasePop
    {
        List<string> _ListPhysics_ID;
        public FormDeviceSearch(List<string> listPhysics_ID)
        {
            InitializeComponent();
            m_comAdatpter.type = (byte)ADSHalConstant.ADS_COMAdapterType.ADS_ADT_TCP;
            m_comAdatpter.address = 0;
            m_comAdatpter.port = 0;

            _ListPhysics_ID = listPhysics_ID;
        }
        ADSHalDataStruct.ADS_Comadapter m_comAdatpter = new ADSHalDataStruct.ADS_Comadapter();
        ADSHalDataStruct.ADS_CommunicationParameter m_comm = new ADSHalDataStruct.ADS_CommunicationParameter();

        private void FormDeviceSearch_Load(object sender, EventArgs e)
        {
            try
            {
                StartWaiting();
                var dt = new DataTable();
                dt.Columns.Add("IsSelct", typeof(bool));
                dt.Columns.Add("ComAdapter_Addr", typeof(string));
                dt.Columns.Add("ComAdapter_Port", typeof(int));
                dt.Columns.Add("ComAdapter_pwd", typeof(int));
                dt.Columns.Add("GetWay", typeof(string));
                dt.Columns.Add("SubnetMask", typeof(string));
                dt.Columns.Add("Device_Type", typeof(string));
                dt.Columns.Add("Physics_ID", typeof(string));
                dt.Columns.Add("IsExists", typeof(bool));
                dt.Columns.Add("Remark", typeof(string));
                uint uRetCount = 0;
                IntPtr[] ptArray = new IntPtr[1];
                ptArray[0] = System.Runtime.InteropServices.Marshal.AllocHGlobal(
                    System.Runtime.InteropServices.Marshal.SizeOf(typeof(ADSHalDataStruct.ADS_ControllerInformation)) * 256);
                IntPtr pt = System.Runtime.InteropServices.Marshal.AllocHGlobal(
                    System.Runtime.InteropServices.Marshal.SizeOf(typeof(ADSHalDataStruct.ADS_ControllerInformation)));
                System.Runtime.InteropServices.Marshal.Copy(ptArray, 0, pt, 1);

                int iResult = ADSHalAPI.ADS_SearchController(ref m_comAdatpter, 1, 256, pt, 256, ref uRetCount);
                if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS && uRetCount > 0)
                {
                    for (int j = 0; j < uRetCount; j++)
                    {
                        var info = (ADSHalDataStruct.ADS_ControllerInformation)System.Runtime.InteropServices.Marshal.PtrToStructure((IntPtr)((UInt32)pt + j * System.Runtime.InteropServices.Marshal.SizeOf(typeof(ADSHalDataStruct.ADS_ControllerInformation)))
                            , typeof(ADSHalDataStruct.ADS_ControllerInformation));
                        var dr = dt.NewRow();
                        dr["ComAdapter_Addr"] = ADSHelp.Int2IP(info.commParam.deviceAddr);
                        dr["ComAdapter_Port"] = info.commParam.devicePort;
                        dr["ComAdapter_pwd"] = info.commParam.password;
                        dr["GetWay"] = ADSHelp.Int2IP(info.commParam.gateway);
                        dr["SubnetMask"] = ADSHelp.Int2IP(info.commParam.subnetMask);
                        dr["Device_Type"] = info.productType;
                        dr["Physics_ID"] = info.deviceID.ToString();
                        if (_ListPhysics_ID.Contains(info.deviceID.ToString()))
                        {
                            dr["IsSelct"] = false;
                            dr["IsExists"] = true;
                            dr["Remark"] = "设备已经存在";
                        }
                        else
                        {
                            dr["IsSelct"] = true;
                            dr["IsExists"] = false;
                            dr["Remark"] = string.Empty;
                        }
                        dt.Rows.Add(dr);
                    }
                }
                System.Runtime.InteropServices.Marshal.FreeHGlobal(ptArray[0]);
                System.Runtime.InteropServices.Marshal.FreeHGlobal(pt);

                this.gridControl1.DataSource = dt;
            }
            finally
            {
                EndWaiting();
            }
        }

        private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (Convert.ToBoolean(gridView1.GetRowCellValue(e.RowHandle, "IsExists")))
                e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Strikeout);
        }
        protected override void FormSave()
        {
            try
            {
                StartWaiting();
                var dt = this.gridControl1.DataSource as DataTable;
                if (dt == null)
                    return;
                dt.AcceptChanges();
                var drs = dt.Select("IsExists=0 and IsSelct=1");
                if (drs.Length < 1)
                {
                    UI.ShowError("没有要添加的设备");
                    return;
                }
                int count = 0;
                foreach (DataRow dr in drs)
                {
                    //ADSHalDataStruct.ADS_ControllerInformation ctrlInfo = new ADSHalDataStruct.ADS_ControllerInformation();
                    //int res = ADSHalAPI.ADS_GetControllerInformation(ref m_comAdatpter, ref m_comm, ref ctrlInfo);
                    //if (res != (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                    //    continue;
                    //var Physics_ID = ctrlInfo.deviceID.ToString();
                    var bal = new BAL.BAL_Device();
                    if (!bal.CheckDevice(dr["ComAdapter_Addr"].ToString(), Convert.ToInt32(dr["ComAdapter_Port"]), dr["Physics_ID"].ToString()))
                    {
                        //UI.ShowError("设备已经存在,请确认后重试");
                        //return;
                        continue;
                    }
                    m_comm.deviceAddr = ADSHelp.IP2Int(dr["ComAdapter_Addr"].ToString());
                    m_comm.devicePort = (ushort)(Convert.ToUInt16(dr["ComAdapter_Port"].ToString()));
                    m_comm.password = (ushort)(Convert.ToUInt16(dr["ComAdapter_pwd"].ToString()));
                    var listSubs = SearchSubs();
                    if (listSubs == null)
                    {
                        //UI.ShowError("检索子设备失败,请稍后重试");
                        //return;
                        continue;
                    }
                    var isok = bal.SaveDevice(
                         string.Empty
                        , dr["Physics_ID"].ToString()
                        , dr["ComAdapter_Addr"].ToString()
                        , dr["Device_Type"].ToString()
                        , string.Empty
                        , string.Empty
                        , dr["ComAdapter_Addr"].ToString()
                        , dr["ComAdapter_Port"].ToString()
                        , dr["ComAdapter_pwd"].ToString()
                        , listSubs
                        );
                    if (isok)
                    {
                        //UI.ShowInfo("保存成功");
                        //this.DialogResult = DialogResult.OK;
                        count += 1;
                    }
                }
                if (count > 0)
                {
                    UI.ShowInfo(string.Format("应保存{0}个,成功保存{1}个", drs.Length, count));
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    UI.ShowError("保存失败");
                    return;
                }
            }
            finally
            {
                EndWaiting();
            }

        }
        private List<ADSHalDataStruct.ADS_LogicSubDeviceInformation> SearchSubs()
        {
            int iResult = ADSHalAPI.ADS_ConnectController(ref Session._ADS_Comadapter, ref m_comm);
            if (iResult != (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
            {
                ADSHelp.PromptResult(iResult, true);
                return null;
            }
            uint m_uLogSudeviceCount = 0;
            /*
               搜索子设备流程：搜索物理子设备，搜索逻辑子设备
            */
            ADSHalDataStruct.ADS_PhysicalSubDeviceInformation[] physicalSubDevices = new ADSHalDataStruct.ADS_PhysicalSubDeviceInformation[64];

            uint uRetCount = 0;

            // 搜索物理子设备
            iResult = ADSHalAPI.ADS_SearchPhysicalSubDevices(ref m_comAdatpter, ref m_comm, ref physicalSubDevices[0], 64, ref uRetCount);

            if (iResult != (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
            {
                ADSHelp.PromptResult(iResult, true);
                return null;
            }
            // 搜索逻辑子设备
            uint uLogicCount = 0;
            //var m_LogicSubDeviceInfo = new ADSHalDataStruct.ADS_LogicSubDeviceInformation[128];
            var m_LogicSubDeviceInfo = new List<ADSHalDataStruct.ADS_LogicSubDeviceInformation>();

            for (uint uIndex = 0; uIndex < uRetCount; uIndex++)
            {
                uLogicCount = 0;

                ADSHalDataStruct.ADS_PhysicalSubDeviceAddress phyphysicalAddr = new ADSHalDataStruct.ADS_PhysicalSubDeviceAddress();
                phyphysicalAddr.physicalSubDevAddr = physicalSubDevices[uIndex].subDevAddr;
                phyphysicalAddr.physicalSubDevID = physicalSubDevices[uIndex].physicalSubDevID;

                IntPtr[] ptArray = new IntPtr[1];
                ptArray[0] = System.Runtime.InteropServices.Marshal.AllocHGlobal(
                    System.Runtime.InteropServices.Marshal.SizeOf(typeof(ADSHalDataStruct.ADS_LogicSubDeviceInformation)) * 32);
                IntPtr pt = System.Runtime.InteropServices.Marshal.AllocHGlobal(
                    System.Runtime.InteropServices.Marshal.SizeOf(typeof(ADSHalDataStruct.ADS_LogicSubDeviceInformation)));
                System.Runtime.InteropServices.Marshal.Copy(ptArray, 0, pt, 1);

                iResult = ADSHalAPI.ADS_SearchLogicSubDevices(ref m_comAdatpter, ref m_comm, ref phyphysicalAddr, pt, 32, ref uLogicCount);

                for (int j = 0; j < uLogicCount; j++)
                {
                    //m_LogicSubDeviceInfo[j + m_uLogSudeviceCount] =
                    //(ADSHalDataStruct.ADS_LogicSubDeviceInformation)System.Runtime.InteropServices.Marshal.PtrToStructure((IntPtr)((UInt32)pt + j * System.Runtime.InteropServices.Marshal.SizeOf(typeof(ADSHalDataStruct.ADS_LogicSubDeviceInformation)))
                    //, typeof(ADSHalDataStruct.ADS_LogicSubDeviceInformation));
                    m_LogicSubDeviceInfo.Add(
                    (ADSHalDataStruct.ADS_LogicSubDeviceInformation)
                    System.Runtime.InteropServices.Marshal.PtrToStructure((IntPtr)((UInt32)pt + j * System.Runtime.InteropServices.Marshal.SizeOf(typeof(ADSHalDataStruct.ADS_LogicSubDeviceInformation)))
                    , typeof(ADSHalDataStruct.ADS_LogicSubDeviceInformation)));
                }
                System.Runtime.InteropServices.Marshal.FreeHGlobal(ptArray[0]);
                System.Runtime.InteropServices.Marshal.FreeHGlobal(pt);
                m_uLogSudeviceCount += uLogicCount;
            }
            return m_LogicSubDeviceInfo;
        }
    }
}
